<template>
	<div v-show="!noData" ref="echartsRef" class="chart-box"></div>
	<el-empty v-show="noData" description="暂无数据" :image-size="80" class="chart-box"></el-empty>
</template>

<script setup lang="ts" name="lineChart">
import { onMounted, ref, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { useEcharts } from '/@/hooks/useEcharts';
const echartsRef = ref<HTMLElement>();

interface Props {
	option: any;
}

// // 默认值
let props = withDefaults(defineProps<Props>(), {
	option: { data: [], xData: [] },
});

const noData = ref(true);

const initChart = (options: any) => {
	if (options.data.flat().length === 0) return;
	const maxNum = Math.max.apply(null, options.data.flat());
	if (!maxNum) return;
	noData.value = false;
	nextTick(() => {
		let myChart: echarts.ECharts = echarts.init(echartsRef.value as HTMLElement);
		let option: echarts.EChartsOption = {
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'cross',
					label: {
						backgroundColor: '#6a7985',
					},
				},
			},
			grid: {
				left: '20px',
				right: '40px',
				bottom: '3%',
				top: options.legend && !options.legendHide ? '60px' : '20px',
				containLabel: true,
			},
			xAxis: [
				{
					type: 'category',
					boundaryGap: false,
					data: options.xData,
					axisLabel: {
						color: '#a1a1a1',
					},
					axisTick: {
						lineStyle: {
							color: '#a1a1a1',
						},
					},
					axisLine: {
						lineStyle: {
							color: '#a1a1a1',
						},
					},
				},
			],
			yAxis: [
				{
					min: Math.floor(Math.min.apply(null, options.data.flat())),
					max: Math.floor(maxNum * 1.2),
					type: 'value',
					axisLabel: {
						color: '#a1a1a1',
					},
					axisLine: {
						lineStyle: {
							color: '#a1a1a1',
						},
					},
				},
			],
			series: [],
		};
		if (options.data) {
			option.series = options.data.map((item: any, index: any) => ({
				name: options.legend[index].name,
				type: 'line',
				emphasis: {
					focus: 'series',
				},
				data: item,
				smooth: true,
			}));
		}
		if (options.legend && !options.legendHide) {
			option['legend'] = {
				left: 20,
				top: 0,
				data: options.legend,
				textStyle: {
					color: '#a1a1a1',
				},
			};
		}
		useEcharts(myChart, option);
	});
};

watch(
	() => props.option,
	(val) => {
		initChart(val);
	},
	{
		deep: true,
	}
);

onMounted(() => {
	initChart(props.option);
});
</script>

<style scoped lang="scss">
@import './chart.scss';
</style>
